﻿/*--------------------------------------------
描述：      客户端常用JS库1.0.0.0
创建时间：   2013年01月01日
创建者：    曾永佑
--------------------------------------------*/

var Global;
if (Global == undefined) {
    Global = {};
    Global.errorShowMode = "tip"; //校验错误显示方式 
    var p = location.href.indexOf("/", location.href.indexOf("//") + 2);
    Global.contextPath = p > -1 ? location.href.substring(0, p) : location.href;
}
/*
*根据参数生成url
*url：url
*param：参数（json）
*addRandomCode：是否在url添加随机数参数（用于避免缓存），默认false
*/
function buildUrl(url, param, addRandomCode) {
    param = param || {};
    addRandomCode = addRandomCode || false;
    if (addRandomCode) {
        param.randomCode = Math.random();
    }
    var paramStr = $.param(param);
    if (paramStr.length > 0)
        return url + "?" + paramStr;
    else
        return url;
}

/*
*如果页面修改，退出时提醒
*selector:jquert选择器，选择要检测发生改变的元素，默认是“input,textarea,select”
*/
function exitPrompt(selector) {
    if (selector == undefined) {
        selector = "input,textarea,select";
    };
    $(selector).bind("change", function () {
        Global.formChanged = true;
    });
    window.onbeforeunload = function (e) {
        try {
            if (Global.formChanged == true && Global.isSubmit != true) {
                var evt = window.event || e;
                evt.returnValue = "离开这个页面您的修改将不会保存";
            }
        } catch (ee) {
        }
    };
    $("form").bind("submit", function () {
        Global.isSubmit = true;
    });
}

// html元素过滤
var security = {};
security.verify = function (actions) {
    $.each(actions, function (i, e) {
        switch (e.Attribute) {
            case "display":
                {
                    $(e.Element).hide();
                }
                break;
            case "visible":
                {
                    $(e.Element).css("visibility", "hidden");
                }
                break;
            case "enabled":
                {
                    $(e.Element).attr("disabled", "true");
                }
                break;
            default:
                {
                    $(e.Element).addClass(e.Attribute);
                }
                break;
        }
    });
};

/*加载树形下拉列表
需要包含jquery.ztree.all.js和zTreeStyle.css
*/
function loadTreeSelector(selectorName, treeData, value) {
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                $("#text-" + selectorName).val(treeNode.name);
                $("input[name='" + selectorName + "']").val(treeNode.id);
                $("#tree-" + selectorName).toggle();
            }
        }
    };

    $.fn.zTree.init($("#tree-" + selectorName), setting, treeData);
    $("#tree-" + selectorName).width($("#text-" + selectorName).width() + 20);
    $(document).bind("click", function (e) {
        if ($(e.target).closest("*[id$='-" + selectorName + "']").length == 0) {
            $("#tree-" + selectorName).hide();
        }
    });
    $("#text-" + selectorName).click(function () {
        var $tree = $("#tree-" + selectorName);
        if ($tree.css("display") == "none") {
            var $text = $("#text-" + selectorName);
            $tree.css("left", $text.position().left);
            $("#tree-" + selectorName).show();
        }
        else {
            $("#tree-" + selectorName).hide();
        }
    });
    $("#reset-" + selectorName).click(function () {
        $("#text-" + selectorName + ",input[name='" + selectorName + "']").val("");
    });
    if (value) {
        var treeObj = $.fn.zTree.getZTreeObj("tree-" + selectorName);
        var node = treeObj.getNodeByParam("id", value);
        if (node) {
            treeObj.selectNode(node);
            $("#text-" + selectorName).val(node.name);
            $("input[name='" + selectorName + "']").val(value);
        }
    }
}
/*初始化选择控件，@Html.SelectorFor 用到该函数
tagId：标签id
readOnly：是否只读
*/
function initSelector(tagId, readOnly) {
    var tag = $("#" + tagId);
    if (!readOnly) {
        $("select", tag).on("change", function () {
            var selectIndex = $(this).get(0).selectedIndex;
            if (selectIndex > 0) {
                var option = $("option:selected", this);
                addItem(option.val());
                $(this).get(0).selectedIndex = 0;
            }
        });
        //显示\隐藏删除图标
        $("span", tag).live("mouseenter", function () {
            $("i", this).css("visibility", "visible");
        }).live("mouseleave", function () {
            $("i", this).css("visibility", "hidden");
        });
        //删除选择项
        $("span i", tag).live("click", function () {
            var id = $(this).parent().attr("key");
            $(this).parent().remove();
            var vals = tag.find("input:hidden").val().split(",");
            var selIds = "";
            for (i = 0; i < vals.length; i++) {
                if (vals[i] != id)
                    selIds += vals[i] + ",";
            }
            selIds = selIds.rtrim(",");
            tag.find("input:hidden").val(selIds);
        });
    }
    if (tag.find("input:hidden").val() != "") {
        vals = tag.find("input:hidden").val().split(",");
        for (i = 0; i < vals.length; i++) {
            addItem(vals[i]);
        }
    }
    //
    function addItem(id) {
        var valTag = tag.find("input:hidden")
        if (!valTag.val().split(",").contains(id)) {
            valTag.val((valTag.val() + "," + id).ltrim(","));
        }
        if (tag.find("span[key='" + id + "']").length == 0) {
            var txt = tag.find("option[value='{0}']".format(id)).text();
            tag.find(".selected-tags").append("<span key='{0}'>{1}<i></i></span>".format(id, txt));
        }
    }
}

/*--------初始化--------*/
$(function () {
    //隔行变色 
    $(".grid>tbody>tr:nth-child(odd)").addClass("odd");
    $(".grid>tbody>tr:nth-child(even)").addClass("even");
});

//jquery扩展函数
(function ($) {
    $.getParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURIComponent(r[2]); return null;
    }
})(jQuery);

//jquery 插件
(function ($) {
    // 搜索
    $.fn.search = function () {
        var formData = {};
        var url = location.href;
        var paraStart = url.indexOf("?") + 1;
        var paras = {};

        //搜索条件 
        this.find("input,select").each(function () {
            var key = $(this).attr("name");
            if (key) {
                formData[key] = $(this).val();
            }
        });
        //url参数
        if (paraStart > 0) {
            $.each($.makeArray(url.substring(paraStart, url.length).split("&")), function () {
                var kv = this.split("=");
                if (kv.length > 0) //只取有值的参数
                    paras[kv[0]] = kv[1];
            });
        }
        $.extend(paras, formData);
        for (var p in paras) {
            if (!paras[p] || paras[p] == "" || p.toLowerCase() == "page")
                delete paras[p];
        }
        if (paraStart > 0)
            url = url.substring(0, paraStart - 1);
        var querystring = $.param(paras);
        if (querystring.length > 0)
            url = url + "?" + querystring;

        location.href = url;
    };
    //初始化搜索栏
    $.fn.initSearch = function () {
        var $searchBar = this;
        $searchBar.find(":text").keydown(function (e) {
            if (e.which == 13) {
                $searchBar.search();
                return false;
            }
        });
        this.find("input:text[name]").each(function () {
            $(this).val($.getParam($(this).attr("name")));
        });
        $searchBar.find(":text:first").focus();
    };
    //jquery 扩展(表单)
    $.fn.fill = function (data) {
        for (var e in data) {
            var elem = $("#" + e + ",input[name='" + e + "']", this);
            var value = data[e];
            if (elem.length > 0) {
                var elemType = elem.attr("type") == undefined ? elem[0].type : elem.attr("type");
                switch (elemType) {
                    case undefined:
                        elem.text(value);
                        break;
                    case "text":
                    case "password":
                    case "hidden":
                    case "textarea":
                        {
                            elem.val(value);
                        }
                }
            }
        }
    };

    //给表格生成序号 
    $.fn.gridsn = function () {
        $(">tbody>tr>td>.rownumber", this).each(function (i) {
            $(this).text(i + 1);
        });
    };

    //jquery 扩展
    $.fn.extend({

        /* 通过ajax请求加载下拉列表
        * url：ajax请求地址
        * param：请求参数
        * label：下拉列表的默认项
        */
        loadOptions: function (url, param, label) {
            var target = $(this);
            target.find("option").remove();
            if (label != undefined) {
                $("<option value=''>" + label + "</option>").appendTo(this);
            }
            $.getJSON(url, param, function (data) {
                for (var p in data) {
                    $("<option value='" + p + "'>" + data[p] + "</option>").appendTo(target);
                }
            });
        },
        tab: function () {
            $(this).children().bind("click", function () {
                $.selectTab($(this));
            });
        },
        showTip: function (keep,fn) {
            var $this = $(this);
            $this.show();
            setTimeout(function () {
                $this.hide();
                if (typeof (fn) == "function") {
                    fn();
                }
            }, keep);
        },

        /*给iframe加载页面并显示等待提示
        * url：页面url地址
        * offset：等待图标偏移位置，{left:-50,top:-50}      
        */
        iframeLoading: function (url, offset) {
            if ($(this).is("iframe")) {
                offset = $.extend({ left: -50, top: -50 }, offset || {});
                var $parent = $(this).parent();
                var divtop = $parent.height() / 2 + offset.top;
                var divleft = $parent.width() / 2 + offset.left;
                $("<div class='loading-large' title='正在加载,请稍候'></div>")
                    .css({ "top": divtop, "left": divleft })
                    .appendTo($parent);

                $(this).on("load", function () {
                    $(".loading-large", $parent).remove();
                });
                if (url && url != "")
                    $(this).attr("src", url);
            }
        }
    });

    //选项卡
    $.selectTab = function (tab) {
        if (typeof (tab) == "string") {
            $.selectTab($("span[key='" + tab + "']"));
        } else {
            tab.parent().children("span").each(function () {
                $(this).removeClass("tab-item-selected");
                var id = "#" + $(this).attr("key");
                $(id).hide();
            });
            tab.addClass("tab-item-selected");
            $("#" + tab.attr("key")).show();
        }
    };

} (jQuery));



/*****扩展函数*************************************************/

/*
* 字符串格式化 ，如
* "{0} is {1}".format("that's","good")
*/
String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[i];
        });
};
String.format = function () {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    var args = arguments;

    return str.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[parseInt(i) + 1];
        });
}

String.prototype.trim = function (str) {
    if (!str)
        str = " "
    reg = new RegExp("^(" + str + "*)|(" + str + "*)$", "gi")
    return this.replace(reg, "")
}
String.prototype.ltrim = function (str) {
    if (!str)
        str = " "
    reg = new RegExp("^(" + str + "*)", "gi")
    return this.replace(reg, "")
}
String.prototype.rtrim = function (str) {
    if (!str)
        str = " "
    reg = new RegExp("(" + str + "*)$", "gi")
    return this.replace(reg, "")
}
/*
* 判断数组是否包含某个值
*/
Array.prototype.contains = function (val, compareFn) {
    if (!compareFn) {
        compareFn = function (a, b) {
            return a == b;
        }
    };
    for (var i = 0; i < this.length; i++) {
        if (this[i] && val && compareFn(this[i], val))
            return true;
    }

    return false;
}
/*
* 获取元素在数组中的索引
*/
Array.prototype.getIndex = function (val, compareFn) {
    if (!compareFn) {
        compareFn = function (a, b) {
            return a == b;
        }
    };
    for (var i = 0; i < this.length; i++) {
        if (this[i] && val && compareFn(this[i], val))
            return i;
    }

    return -1;
}
/******************************************************/

